"""
Zypper包管理器实现
支持openSUSE和SUSE系统
"""

import subprocess
from ..core import OnlinePackageManager


class ZypperManager(OnlinePackageManager):
    """Zypper包管理器"""
    
    def __init__(self, sudo=False):
        super(ZypperManager, self).__init__(sudo)
        self.name = "zypper"
        self.description = "SUSE/openSUSE包管理器"
        
    def is_available(self):
        """检查zypper是否可用"""
        try:
            result = subprocess.run(
                ["zypper", "--version"],
                capture_output=True,
                text=True,
                check=False
            )
            return result.returncode == 0
        except (subprocess.SubprocessError, FileNotFoundError):
            return False
    
    def update(self):
        """更新包数据库"""
        cmd = ["zypper", "refresh"]
        if self.sudo:
            cmd = ["sudo"] + cmd
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            return result.returncode == 0
        except subprocess.SubprocessError:
            return False
    
    def upgrade(self):
        """升级所有包"""
        cmd = ["zypper", "update", "-y"]
        if self.sudo:
            cmd = ["sudo"] + cmd
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            return result.returncode == 0
        except subprocess.SubprocessError:
            return False
    
    def install(self, packages):
        """安装包"""
        if not packages:
            return False
            
        cmd = ["zypper", "install", "-y"] + packages
        if self.sudo:
            cmd = ["sudo"] + cmd
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            return result.returncode == 0
        except subprocess.SubprocessError:
            return False
    
    def remove(self, packages):
        """移除包"""
        if not packages:
            return False
            
        cmd = ["zypper", "remove", "-y"] + packages
        if self.sudo:
            cmd = ["sudo"] + cmd
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            return result.returncode == 0
        except subprocess.SubprocessError:
            return False
    
    def search(self, pattern):
        """搜索包"""
        cmd = ["zypper", "search", pattern]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            if result.returncode != 0:
                return []
            
            packages = []
            lines = result.stdout.strip().split('\n')
            
            # 跳过表头
            start_processing = False
            for line in lines:
                if line.startswith('--'):
                    start_processing = True
                    continue
                
                if start_processing and line.strip():
                    parts = line.split('|')
                    if len(parts) >= 3:
                        name = parts[1].strip()
                        version = parts[2].strip()
                        description = parts[3].strip() if len(parts) > 3 else ""
                        
                        packages.append({
                            'name': name,
                            'version': version,
                            'description': description,
                            'repository': 'zypper'
                        })
            
            return packages
        except subprocess.SubprocessError:
            return []
    
    def info(self, package):
        """获取包信息"""
        cmd = ["zypper", "info", package]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            if result.returncode != 0:
                return None
            
            info = {}
            for line in result.stdout.strip().split('\n'):
                if ':' in line:
                    key, value = line.split(':', 1)
                    key = key.strip().lower().replace(' ', '_')
                    value = value.strip()
                    info[key] = value
            
            return {
                'name': package,
                'version': info.get('version', ''),
                'description': info.get('summary', ''),
                'size': info.get('size', ''),
                'repository': info.get('repository', '')
            }
        except subprocess.SubprocessError:
            return None
    
    def list_installed(self):
        """列出已安装的包"""
        cmd = ["zypper", "search", "-i"]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            if result.returncode != 0:
                return []
            
            packages = []
            lines = result.stdout.strip().split('\n')
            
            # 跳过表头
            start_processing = False
            for line in lines:
                if line.startswith('--'):
                    start_processing = True
                    continue
                
                if start_processing and line.strip():
                    parts = line.split('|')
                    if len(parts) >= 3:
                        name = parts[1].strip()
                        version = parts[2].strip()
                        
                        packages.append({
                            'name': name,
                            'version': version,
                            'architecture': ''
                        })
            
            return packages
        except subprocess.SubprocessError:
            return []
    
    def installed(self, package):
        """检查包是否已安装"""
        cmd = ["zypper", "search", "-i", package]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            return result.returncode == 0 and package in result.stdout
        except subprocess.SubprocessError:
            return False
    
    def clean_cache(self):
        """清理包缓存"""
        cmd = ["zypper", "clean"]
        if self.sudo:
            cmd = ["sudo"] + cmd
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            return result.returncode == 0
        except subprocess.SubprocessError:
            return False